import {DesktopOutlined, PieChartOutlined} from "@ant-design/icons";
import {Menu, MenuProps} from 'antd';
import React, {useEffect, useState} from "react";
import {useLocation, useNavigate} from "react-router-dom";
import {useTheme} from "@/contexts/ThemeContext.tsx";

type MenuItem = Required<MenuProps>['items'][number];

interface LevelKeysProps {
    key?: string;
    children?: LevelKeysProps[];
}

function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
): MenuItem {
    return {
        key,
        icon,
        children,
        label,
    } as MenuItem;
}

const items: MenuItem[] = [
    getItem('首页', '/home', <PieChartOutlined/>),
    getItem('关于', '/about', <DesktopOutlined/>),
    getItem('页面3', '/page3', <DesktopOutlined/>, [
        getItem('页面301', '/page3/page301', <DesktopOutlined/>),
        getItem('页面302', '/page3/page302', <DesktopOutlined/>),
    ])
]

const Comp = () => {

    const {theme} = useTheme();
    const navigate = useNavigate()
    const currentRoute = useLocation().pathname
    const [stateOpenKeys, setStateOpenKeys] = useState([""]);

    // 根据当前路径，动态展开菜单
    useEffect(() => {
        // 自动展开父级菜单（如果路径是子菜单）
        const parentKey = currentRoute.split('/').slice(0, 2).join('/'); // 提取父路径 "/dashboard"
        console.log("parentKey:", parentKey);
        if (parentKey !== currentRoute) {
            setStateOpenKeys(prev => [...new Set([...prev, parentKey])]);
        }
    }, [currentRoute]);


    /**
     * 菜单展开回调
     * @param items1
     */
    const getLevelKeys = (items1: LevelKeysProps[]) => {

        const key: Record<string, number> = {};
        const func = (items2: LevelKeysProps[], level = 1) => {
            items2.forEach((item) => {
                if (item.key) {
                    key[item.key] = level;
                }
                if (item.children) {
                    func(item.children, level + 1);
                }
            });
        };
        func(items1);
        return key;
    };

    const levelKeys = getLevelKeys(items as LevelKeysProps[]);


    /**
     * 菜单点击事件
     * @param item
     */
    const menuClick = (item: { key: string }) => {
        navigate(item?.key)
    }


    /**
     * 改变父菜单展开
     * @param openKeys
     */
    const onOpenChange: MenuProps['onOpenChange'] = (openKeys) => {
        const currentOpenKey = openKeys.find((key) => stateOpenKeys.indexOf(key) === -1);
        // open
        if (currentOpenKey !== undefined) {
            const repeatIndex = openKeys
                .filter((key) => key !== currentOpenKey)
                .findIndex((key) => levelKeys[key] === levelKeys[currentOpenKey]);

            setStateOpenKeys(
                openKeys
                    // remove repeat key
                    .filter((_, index) => index !== repeatIndex)
                    // remove current level all child
                    .filter((key) => levelKeys[key] <= levelKeys[currentOpenKey]),
            );
        } else {
            // close
            setStateOpenKeys(openKeys);
        }
    };


    return (
        <Menu theme={theme} defaultSelectedKeys={[currentRoute]} mode="inline" items={items}
              onClick={menuClick} openKeys={stateOpenKeys} onOpenChange={onOpenChange}/>
    );
};

export default Comp;